import type { Directive, DirectiveBinding } from 'vue'
interface ElType extends HTMLElement {
  __vueScrollBottomHandler__: any
}

const scroll: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    const handler = function () {
      const { scrollTop, scrollHeight, clientHeight } = el
      if (scrollTop + clientHeight >= scrollHeight) {
        if (typeof binding.value === 'function') {
          binding.value()
        }
      }
    }
    el.addEventListener('scroll', handler)
    el.__vueScrollBottomHandler__ = handler // 存储引用
  },
  beforeUnmount(el: ElType) {
    if (el.__vueScrollBottomHandler__) {
      el.removeEventListener('scroll', el.__vueScrollBottomHandler__)
      delete el.__vueScrollBottomHandler__ // 清理引用
    }
  },
}

export default scroll
